const sqlite3 = require('sqlite3').verbose();
const db = new sqlite3.Database('./data/database.db');

// 初始化数据库表
function initializeDatabase() {
  db.serialize(() => {
    db.run('CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY AUTOINCREMENT, nickName TEXT, email TEXT)');
  });
}

// 创建用户
function createUser(userData) {
  return new Promise((resolve, reject) => {
    db.run(
      'INSERT INTO users (nickName, email) VALUES (?, ?)',
      [userData.nickName, userData.email],
      function (err) {
        if (err) {
          reject(err);
        } else {
          resolve({ id: this.lastID, ...userData });
        }
      }
    );
  });
}

// 获取所有用户
function getAllUsers() {
  return new Promise((resolve, reject) => {
    if (!db) {
      reject(new Error('Database connection is not initialized'));
      return;
    }
    db.all('SELECT * FROM users', [], (err, rows) => {
      if (err) {
        reject(err);
      } else if (!rows) {
        reject(new Error('No data returned from the database'));
      } else {
        resolve(rows);
      }
    });
  });
}

initializeDatabase();

module.exports = {
  db,
  createUser,
  getAllUsers,
  initializeDatabase,
};